package com.zenchn.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.zenchn.annotation.OperLog;
import com.zenchn.entity.*;
import com.zenchn.enums.OperLogActionEnum;
import com.zenchn.exception.CheckException;
import com.zenchn.external.service.FileGenericStrategy;
import com.zenchn.model.TSysFile;
import com.zenchn.model.TSysFileExample;
import com.zenchn.model.TSysWebStyleConfig;
import com.zenchn.model.TSysWebStyleConfigExample;
import com.zenchn.service.SysFileService;
import com.zenchn.service.WebStyleConfigService;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.util.*;

/**
 * 平台自定义信息配置 控制层
 * @author dingxinfa
 * @date 2020-06-12
 */
@RestController
@RequestMapping(value = "platformConfig")
@Api(value = "平台自定义信息配置接口",tags="系统管理-平台信息")
@RequiresPermissions("platform:info")
public class PlatformConfigController {

    private final String MODULE = "系统管理>平台信息";


    @Resource
    private WebStyleConfigService webStyleConfigService;

    @Resource
    private SysFileService sysFileService;

    @Resource
    private FileGenericStrategy fileGenericStrategy;

    @Resource
    private SysConfig sysConfig;

    /***
     * 文件保存临时目录
     */
    @Value("${custom.file.temp.path}")
    private String tmpPath;

    @Value("${custom.platform.version}")
    private String platformVersion;


    /**
     * 当前机构平台自定义配置信息
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.QUERY, detail = "平台自定义配置信息", isSaveRequestData = false)
    @ApiOperation(value = "平台自定义配置信息", notes = "平台自定义配置信息")
    @GetMapping(value = "/configDetail")
    public ResponseEntity<HttpDataResult<PlatformConfigVO>> platformConfigDetail(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<PlatformConfigVO> result = new HttpDataResult<>(request.getRequestURI());

        PlatformConfigVO platformConfigVO=new PlatformConfigVO();
        platformConfigVO.setPlatformVersion(platformVersion);

        TSysWebStyleConfigExample webStyleConfigExample=new TSysWebStyleConfigExample();
        webStyleConfigExample.createCriteria().andIsGenericEqualTo(true);
        webStyleConfigExample.setOrderByClause("is_generic desc limit 1");
        List<TSysWebStyleConfig> webStyleConfigList=webStyleConfigService.selectByExample(webStyleConfigExample);
        TSysWebStyleConfig webStyleConfig=new TSysWebStyleConfig();

        if (null==webStyleConfigList|| webStyleConfigList.isEmpty()){
            webStyleConfig.setStyleConfigId("00000000000000000000000000000000");
            webStyleConfig.setIsGeneric(true);
            webStyleConfigService.insertSelective(webStyleConfig);
        }else{
            webStyleConfig=webStyleConfigList.get(0);
        }

        platformConfigVO.setPlatformName(webStyleConfig.getPlatformName());
        platformConfigVO.setIconFileId(webStyleConfig.getIconFileId());
        platformConfigVO.setLogoFileId(webStyleConfig.getLogoFileId());
        platformConfigVO.setCopyright(webStyleConfig.getCopyright());
        platformConfigVO.setPlatformStyle(webStyleConfig.getPlatformStyle());
        platformConfigVO.setAccessParameter(webStyleConfig.getAccessParameter());

        List<String>  carouselImageIds = JSONObject.parseArray(webStyleConfig.getCarouselImageIds(), String.class);

        if (null != platformConfigVO.getIconFileId() && !"".equals(platformConfigVO.getIconFileId())) {
            TSysFile sf = sysFileService.selectByPrimaryKey(platformConfigVO.getIconFileId());
            platformConfigVO.setIconFileUrl(sysConfig.getCurrentUseFormalFileUrl() + "/" + sf.getFilePath());
        }

        if (null != platformConfigVO.getLogoFileId() && !"".equals(platformConfigVO.getLogoFileId())) {
            TSysFile sf = sysFileService.selectByPrimaryKey(platformConfigVO.getLogoFileId());
            platformConfigVO.setLogoFileUrl(sysConfig.getCurrentUseFormalFileUrl() + "/" + sf.getFilePath());
        }
        if (null != carouselImageIds&& !carouselImageIds.isEmpty()) {
            TSysFileExample fileExample=new TSysFileExample();
            fileExample.createCriteria().andFileIdIn(carouselImageIds);
            List<TSysFile> fileList=sysFileService.selectByExample(fileExample);

            List<Map<String,String>> carouselImageList = new ArrayList<>();
            fileList.forEach(file ->{
                String url=sysConfig.getCurrentUseFormalFileUrl() + "/" + file.getFilePath();
                carouselImageList.add(ImmutableMap.of("fileId",file.getFileId(),"url",url));
            });

            platformConfigVO.setCarouselImageList(carouselImageList);
        }


        result.setData(platformConfigVO);

        result.setMessage("OK.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }


    /***
     * 修改自定义配置保存提交
     * @param platformConfigDO
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.UPDATE, detail = "平台信息修改提交")
    @ApiOperation(value = "平台信息修改提交", notes = "平台信息修改提交")
    @ApiParam(type = "PlatformConfigDO", name = "platformConfigDO", value = "平台信息提交对象", required = true)
    @PutMapping(value = "/platformConfigSubmit")
    public ResponseEntity<HttpResult> platformConfigSubmit(
            @RequestBody @Valid PlatformConfigDO platformConfigDO, BindingResult results,

            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpResult result = new HttpResult(request.getRequestURI());

        if (results.hasErrors()){
            throw new CheckException(Objects.requireNonNull(results.getFieldError()).getDefaultMessage());
        }

        TSysWebStyleConfigExample webStyleConfigExample=new TSysWebStyleConfigExample();
        webStyleConfigExample.createCriteria().andIsGenericEqualTo(true);
        webStyleConfigExample.setOrderByClause("is_generic desc limit 1");
        List<TSysWebStyleConfig> webStyleConfigList=webStyleConfigService.selectByExample(webStyleConfigExample);
        TSysWebStyleConfig webStyleConfig=new TSysWebStyleConfig();

        if (null==webStyleConfigList|| webStyleConfigList.isEmpty()){
            webStyleConfig.setStyleConfigId("00000000000000000000000000000000");
            webStyleConfig.setIsGeneric(true);
            webStyleConfigService.insertSelective(webStyleConfig);
        }else{
            webStyleConfig=webStyleConfigList.get(0);
        }

        if (!webStyleConfigService.verifyName(webStyleConfig.getStyleConfigId(),platformConfigDO.getAccessParameter())){
            throw new CheckException("访问参数重复，无法修改保存提交！");
        }

        //平台名称
        if (null!=platformConfigDO.getPlatformName()){
            webStyleConfig.setPlatformName(platformConfigDO.getPlatformName());
        }

        //icon
        List<String> iconFileIds= saveTempFile(platformConfigDO.getIconFileSet(), request);
        if (null!=iconFileIds){
            //删除老图
            if (null!=webStyleConfig.getIconFileId() && !"".equals(webStyleConfig.getIconFileId().trim())){
                fileGenericStrategy.deleteFile(webStyleConfig.getIconFileId());
            }
            webStyleConfig.setIconFileId(iconFileIds.get(0));
        }

        //logo
        List<String> logoFileIds= saveTempFile(platformConfigDO.getLogoFileSet(), request);
        if (null!=logoFileIds){
            //删除老图
            if (null!=webStyleConfig.getLogoFileId() && !"".equals(webStyleConfig.getLogoFileId().trim())){
                fileGenericStrategy.deleteFile(webStyleConfig.getLogoFileId());
            }
            webStyleConfig.setLogoFileId(logoFileIds.get(0));
        }


        //版权信息
        if (null!=platformConfigDO.getCopyright()){
            webStyleConfig.setCopyright(platformConfigDO.getCopyright());
        }

        //风格样式
        if (null!=platformConfigDO.getPlatformStyle()){
            webStyleConfig.setPlatformStyle(platformConfigDO.getPlatformStyle());

        }

        //访问参数
        if (null!=platformConfigDO.getAccessParameter()){
            webStyleConfig.setAccessParameter(platformConfigDO.getAccessParameter());
        }

        //轮播图片

        //删除老图
        List<String>  originalCarouselImageIds=null;
        if (null!=webStyleConfig.getCarouselImageIds()){
            originalCarouselImageIds = JSONObject.parseArray(webStyleConfig.getCarouselImageIds(), String.class);
            if (null!=originalCarouselImageIds && !originalCarouselImageIds.isEmpty()) {
                if (null != platformConfigDO.getDelCarouselImageFileIdList()) {
                    platformConfigDO.getDelCarouselImageFileIdList().forEach(delFileId -> {
                        fileGenericStrategy.deleteFile(delFileId);
                    });
                    originalCarouselImageIds.removeAll(platformConfigDO.getDelCarouselImageFileIdList());
                }
            }
        }

        //添加新图
        List<String> carouselImageFileIds= saveTempFile(platformConfigDO.getCarouselImageFileSet(), request);
        if (null!=carouselImageFileIds){
            if(null == originalCarouselImageIds){
                originalCarouselImageIds = new ArrayList<>();
            }
            originalCarouselImageIds.addAll(carouselImageFileIds);
        }
        webStyleConfig.setCarouselImageIds(JSON.toJSONString(originalCarouselImageIds));
        webStyleConfigService.updateByPrimaryKey(webStyleConfig);
        result.setMessage("OK");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /***
     * 保存上传的临时文件
     * @param fileSet
     * @param request
     * @return
     */
    private List<String> saveTempFile(String fileSet, HttpServletRequest request){
        if (request.getSession().getAttribute(fileSet) != null) {
            LinkedList<FileMeta> fileMetaList = (LinkedList<FileMeta>) request.getSession().getAttribute(fileSet);
            request.getSession().removeAttribute(fileSet);

            if (null!=fileMetaList && !fileMetaList.isEmpty()) {
                List<String> fileIds=new ArrayList<>();
                fileMetaList.forEach(fileMeta  ->{
                    File file = new File(tmpPath + "//" + fileMeta.getSaveFilePath());
                    JsonResult<Map> jsonResult = fileGenericStrategy.simpleFileUpload("platformConfig", file, fileMeta.getFileName());
                    if (jsonResult.getSuccess()) {
                        fileIds.add((String) jsonResult.getData().get("fileId"));
                    }
                });
                return fileIds;
            }
        }
        return null;
    }


    /***
     * 验证访问参数唯一性
     * @param styleConfigId
     * @param accessParameter
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module = MODULE, action = OperLogActionEnum.CHECK, detail = "验证访问参数唯一性", isSaveRequestData = true)
    @ApiOperation(value = "验证访问参数唯一性", notes = "验证访问参数唯一性")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "styleConfigId", value = "平台配置ID", required = false),
            @ApiImplicitParam(dataType = "String", name = "accessParameter", value = "访问参数", required = true)
    })
    @GetMapping(value = "/verifyName")
    public ResponseEntity<HttpDataResult<Boolean>> verifyName(
            @RequestParam(required = false, value = "styleConfigId") String styleConfigId,
            @RequestParam(value = "accessParameter") String accessParameter,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());

        result.setData(webStyleConfigService.verifyName(styleConfigId,accessParameter));

        result.setMessage("验证访问参数唯一性成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);

    }

}
